from django import template
from django.conf import settings
from django.http import QueryDict
from django.urls import reverse
from django.utils.safestring import mark_safe

register = template.Library()


def check_permission(request, url_name):
    # 1. 获取当前用户角色
    role = request.my_user.role
    # 2. 获取当前角色权限
    permission = settings.MY_PERMISSION
    # 3. 判断当前用户权限
    return url_name in permission.get(role)


@register.simple_tag
def add_permission(request, url_name, *args, **kwargs):
    has_permission = check_permission(request, url_name)
    # 4. 无权限，返回空
    if not has_permission:
        return ''
    # 5. 有权限，返回对应权限按钮
    url = reverse(url_name, args=args, kwargs=kwargs)
    tpl = f'''
            <a href="{url}" class="btn btn-success">
                <i class="fas fa-plus-circle"></i>
                <span> 添加</span>
            </a>
    '''
    return mark_safe(tpl)


@register.simple_tag
def edit_permission(request, url_name, *args, **kwargs):
    has_permission = check_permission(request, url_name)
    # 4. 无权限，返回空
    if not has_permission:
        return ''
    # 5. 有权限，返回对应权限按钮
    ori_param = request.GET.urlencode()
    new_query_dict = QueryDict(mutable=True)
    new_query_dict.update({'_filter': ori_param})
    encode_param = new_query_dict.urlencode()
    url = reverse(url_name, args=args, kwargs=kwargs) + '?' + encode_param
    tpl = f'''<a href="{url}" class="btn btn-xs btn-primary">编辑</a>'''
    return mark_safe(tpl)


@register.simple_tag
def delete_permission(request, url_name, *args, **kwargs):
    has_permission = check_permission(request, url_name)
    # 4. 无权限，返回空
    if not has_permission:
        return ''
    # 5. 有权限，返回对应权限按钮
    cid = kwargs.get('cid')
    tpl = f'''<a href="#" class="btn btn-xs btn-danger btn-delete" cid="{cid}">删除</a>'''
    return mark_safe(tpl)


@register.filter
def td_permission(request, others):
    permissions = others.split(',')
    for permission in permissions:
        if check_permission(request, permission):
            return True
